package com.hh.bss.auth.filter;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hh.bss.auth.client.OnlineManager;
import com.hh.bss.common.cache.SystemUserCache;
import com.hh.bss.config.Environment;
import com.hh.bss.util.extjs.JsonHelper;

public class LoginFilter extends HttpServlet implements Filter {

	private final int HAS_PERMISSION = 0, NOT_LOGIN = 1, NO_PERMISSION = 2;

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;

		HttpServletResponse resp = (HttpServletResponse) response;

		// 以下页面需要检查是否登录
		int status = HAS_PERMISSION;//
		OnlineManager manager = new OnlineManager(req, resp);
		String pageURI = req.getRequestURI().replaceFirst(req.getContextPath(), "");
		// 取得访问功能点的名称
		String urlName = manager.getResourceName();
		String ip = req.getRemoteAddr();
		System.out.println("客户IP:" + ip);
		if (manager.isSignIn()) { // 判断是否登录
			// 验证Ip 和权限
			// if (!"admin".equals(manager.getOnlineUser().getUsername())) {
			System.out.println("登录用户:" + manager.getOnlineUser().getUsername());
			if (!SystemUserCache.validateIP(ip)) {
				System.out.println("IP 验证失败...");
				if (!manager.hasPermission("/auth/systemUser/userlogin.do")) {
					// 清除Cookie
					manager.signOut();
					// 进入权限
					System.out.println("权限验证未通过");
					Map<String, Object> result = new HashMap<String, Object>();
					result.put("success", false);
					result.put("msg", "登录失败,由于您不是在办公室登陆,IP受限,请联系管理员取得相应的授权.");
					resp.sendRedirect("/login.html");
					outJson(resp, result);
					return;
				} else {
					System.out.println("权限验证通过");
				}
			}

		}

		// }
		if (this.isIgnorePage(req, resp) == false) {
			// 以下页面需要检查是否登录
			// OnlineAdminManager manager = new OnlineAdminManager(req,resp);
			if (manager.isSignIn() == false) {
				// 未登录
				status = NOT_LOGIN;
			} else if (!manager.hasPermission()) {
				// 没有权限访问此页面
				status = NO_PERMISSION;
			}
		}

		switch (status) {
		case NOT_LOGIN:
			resp.sendRedirect("/login.html");
			return;
		case NO_PERMISSION: {
			// 特殊的只返回提示
			if (isSpecUrl(pageURI)) {
				JsonHelper.outJsonString(resp, "对不起，您没有\"" + urlName + "\"操作权限!");
			} else {
				Map<String, Object> result = new HashMap<String, Object>();
				result.put("list", new ArrayList());
				result.put("success", false);
				result.put("msg", "对不起，您没有\"" + urlName + "\"操作权限!");
				result.put("message", "对不起，您没有\"" + urlName + "\"操作权限!");
				result.put("errorMessage", "对不起，您没有\"" + urlName + "\"操作权限!");
				outJson(resp, result);
			}

			return;
		}
		default:

		}
		filterChain.doFilter(request, response);

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	private boolean isSpecUrl(String url) {
		// 报表下载
		System.out.println(url);
		if (url.startsWith("/report/report") && url.indexOf("down.do") >= 0)
			return true;
		return false;
	}

	private boolean isIgnorePage(HttpServletRequest req, HttpServletResponse response) {
		// 以下页面忽略联盟站点登录检验：联盟登录页，联盟登录检验页
		String[] ignores = Environment.IGNORE_PAGES.split(",");
		for (int i = 0; i < ignores.length; i++) {
			String rule = req.getContextPath() + ignores[i];
			Pattern p = Pattern.compile(rule);
			Matcher m = p.matcher(req.getRequestURI());
			if (m.matches())
				return true;
		}
		return false;
	}

}
